<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon" ref="mainCon">
      <el-row
        class="toolbar searchInputWidth"
        :style="{
          paddingBottom: 0,
          marginBottom: formData.problemArr.length > 1 ? '20px' : '',
        }"
      >
        <p class="title">
          预览建议书<span class="subTitle"
            >(共计{{ tableList.length }}个建议书)</span
          >
        </p>
        <el-form
          :inline="true"
          :model="formData"
          ref="searchConditions"
          label-width="80px"
        >
          <el-form-item label="区域" class="row-padding-bottom">
            <el-cascader
              v-model="formData.areaArr"
              :options="areaList"
              placeholder="请选择"
              clearable
              style="width: 98%"
              ref="manageArea"
              @change="getAreaId"
              filterable
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="行业" class="row-padding-bottom">
            <el-select
              v-model="formData.rangeIndustry"
              filterable
              placeholder="请选择"
              clearable
              style="width: 98%"
            >
              <el-option
                v-for="item in industryList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="问题类型"
            class="row-padding-bottom problemSelect"
          >
            <el-select
              v-model="formData.pid"
              filterable
              placeholder="请选择"
              clearable
              @change="changeProblem"
            >
              <!--<el-option v-for="(item,index) in problemList" :key="item.id" :label="item.reason" :value="item.indexId"></el-option>-->
              <el-tooltip
                placement="bottom"
                v-for="(item, index) in problemList"
                :key="item.id"
              >
                <div slot="content">
                  <div :style="{ maxWidth: '200px', wordBreak: 'break-all' }">
                    {{ item.reason }}
                  </div>
                </div>
                <el-option
                  :label="item.reason.substring(0, 16) + '...'"
                  :value="item.schemeId"
                ></el-option>
              </el-tooltip>
            </el-select>
          </el-form-item>

          <div :style="{ display: isBigScreen ? 'block' : 'inline-block' }">
            <el-form-item
              label="工程项目"
              class="row-padding-bottom"
              v-if="isBigScreen"
            >
              <el-input
                v-model="formData.projectName"
                placeholder="输入项目名称"
                clearable
                class="scopeInputWidth"
              ></el-input>
            </el-form-item>
            <el-form-item class="row-padding-bottom">
              <div class="openBtn" @click="isBigScreen = !isBigScreen">
                {{ isBigScreen ? '收起' : '展开' }}&nbsp;<i
                  class="el-icon-arrow-down"
                  :class="[isBigScreen ? 'down' : 'up']"
                ></i>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="commonBtn"
              ></el-button>
            </el-form-item>
            <el-form-item label-width="100px"></el-form-item>
          </div>
        </el-form>
      </el-row>

      <el-table
        :data="
          tableList.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        :row-key="recordId"
      >
        <el-table-column prop="mainName" label="用工主体"></el-table-column>
        <el-table-column
          prop="projectName"
          label="工程名称"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="quesDtoList.length"
          label="用工问题"
        ></el-table-column>
        <el-table-column label="操作" align="left" fixed="right">
          <template slot-scope="scope">
            <el-link type="primary" @click="topreview(scope.row)"
              >预览建议书</el-link
            >
            <el-link type="primary" @click="toDelete(scope.row)">删除</el-link>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty">
          <p>暂无相关数据</p>
        </div>
      </el-table>
      <div>
        <el-col :span="24" class="toolbar" style="text-align: right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSizeNumber"
            layout="prev, pager, next, sizes, jumper"
            :total="tableList.length"
            ref="pagination"
          ></el-pagination>
        </el-col>
      </div>

      <div class="submitBox">
        <el-button
          type="primary"
          class="commonBut saveBtn"
          @click="saveForm"
          :loading="isSaveLoading"
        >
          确定创建
        </el-button>
        <el-button class="commonBut" @click="goBack"> 返回上一步 </el-button>
      </div>
    </div>

    <preview-dialog :previewData="formDataView" ref="previewDialog" />
    <notice-dialog
      ref="noticeDialog"
      @changeNotice="changeNotice"
      @sure="sure"
    />
    <zero-dialog ref="zeroDialog" />
  </div>
</template>

<script>
import topTitle from '@/components/publicCom/topTitle'
import previewDialog from '@/components/onlineLaw/previewDialog'
import noticeDialog from '@/components/onlineLaw/noticeDialog'
import zeroDialog from '@/components/onlineLaw/zeroDialog'

export default {
  name: 'previewProposal',
  components: {
    topTitle,
    previewDialog,
    noticeDialog,
    zeroDialog,
  },

  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      pageSizeNumber: 5,
      pageSizes: [5, 10, 15, 20],
      formData: { pid: '' },
      industryList: [], //项目范围，行业
      areaList: [], //项目范围，地区
      titleText: '返回列表',
      back: true,
      statusData: [], //建议书状态
      areasOptions: [], //区域
      industryOptions: [], //行业
      //表格数据
      tableList: [],
      requestUrl: 'api-ps/enforce/config/match',
      areaId: '', //区域
      industryId: '', //行业

      formDataView: null,
      isSaveLoading: false, //确认创建
      companyId: '', //跳转详情传参
      loading: true,
      isBigScreen: false,
      checkedId: [], //列表选中id数组
      problemList: [], //用工问题
    }
  },
  created() {
    //获取行业
    this.getIndustry()
    //获取区域
    this.getArea()
    console.log(this.$store.state.proposalData)
    if (this.$store.state.proposalData) {
      this.formData = this.$store.state.proposalData.data
      let ppp = this.$store.state.proposalData.problemList
      this.problemList.push({
        dimId: '1',
        dimName: '全部问题',
        id: '',
        indexId: '',
        indexName: '全部问题',
        method: null,
        reason: '全部问题',
        schemeId: '',
        status: null,
        statusStr: null,
        tip: '全部问题',
        tips: null,
        updateTime: null,
      })
      ppp.forEach((it) => {
        this.problemList.push(it)
      })

      this.formDataView = this.formData

      this.match()
    }
  },
  methods: {
    changeProblem(e) {
      console.log(e)
      this.formData.pid = e
      this.$forceUpdate()
    },
    goBack() {
      this.$router.push('/home/onlineLaw/addProposal')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/onlineLaw/previewProposal',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //获取选中的区域最后一级id
    getAreaId() {
      this.formData.rangeArea =
        this.formData.areaArr[this.formData.areaArr.length - 1]
    },
    getIndustry() {
      const that = this
      this.axios({
        method: 'get',
        url: 'api-bs/base/dicitem/getuserindustry',
      })
        .then((res) => {
          if (res && res.data) {
            that.industryList = [
              { code: '', name: '全部行业' },
              ...res.data.result,
            ]
          }
        })
        .catch((error) => {
          that.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    getArea() {
      const that = this
      let areaId = localStorage.getItem('areaId')
      this.axios({
        method: 'get',
        url: 'api-bs/areadic/base/detailbyareaid',
        params: { areaId: areaId },
      })
        .then((res) => {
          if (res && res.data) {
            that.areaList = res.data.result
          }
        })
        .catch((error) => {
          that.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    // 搜索
    searchList() {
      this.loading = true
      this.currentPage = 1
      this.match()
    },
    match() {
      this.formData.problemId = []
      if (this.formData.pid) {
        this.formData.problemId.push(this.formData.pid)
      } else {
        this.problemList.forEach((it) => {
          if (it.schemeId) {
            this.formData.problemId.push(it.schemeId)
          }
        })
      }
      this.axios({
        method: 'POST',
        url: 'api-ps/enforce/config/match',
        data: this.formData,
        headers: {
          'Content-Type': 'application/json', //设置请求头请求格式为JSON
        },
      })
        .then((resp) => {
          this.loading = false
          if (
            !resp.data.hasError &&
            resp.data.result &&
            resp.data.result.length > 0
          ) {
            this.tableList = resp.data.result

            console.log(this.tableList.quesDtoList)

            this.tableList.forEach((it) => {
              it.quesDtoList.forEach((t) => {
                t.reason = t.reason.replaceAll('1、扣分原因：', '')
                t.reason = t.reason.replaceAll('2、扣分明细：', '')
                t.tip = t.tipStr
                t.tipStr = '<div class="tipBox">' + t.tipStr + '</div>'
              })
            })
          } else {
            this.tableList = []
          }
        })
        .catch((resp) => {
          this.loading = false
          console.log('请求失败：' + resp.status + ',' + resp.statusText)
        })
    },

    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    recordId(row) {
      return row.id
    },
    topreview(row) {
      this.formDataView.problemArr = row.quesDtoList
      this.formDataView.showProjectName = row.projectName
      this.formDataView.showCompanyName = row.mainName
      this.$refs.previewDialog.showDialog()
    },

    toDelete(row) {
      this.$alert('是否删除该建议书', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        let index = this.tableList.findIndex((item) => {
          return item.mainId === row.mainId
        })
        this.tableList.splice(index, 1)

        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      })
    },
    saveForm() {
      if (this.tableList.length <= 0) {
        this.$refs.zeroDialog.showDialog()
        return
      }
      this.$refs.noticeDialog.showDialog()
    },
    changeNotice(val) {
      //选择短信通知
      console.log(typeof val)
      if (val) {
        this.formData.sms = 1
      } else {
        this.formData.sms = 0
      }
    },
    sure() {
      const loading = this.$loading({
        lock: true, //lock的修改符--默认是false
        text: '', //显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', //自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', //遮罩层颜色
        target: document.querySelector('body'), //loadin覆盖的dom元素节点
      })

      this.formData.matchDtoList = this.tableList
      this.formData.problemId = []
      if (this.formData.pid) {
        this.formData.problemId.push(this.formData.pid)
      }
      console.log(this.formData, 'xxxxxxxxxxxxxxxxxxxxxxx')
      this.axios({
        method: 'POST',
        url: 'api-ps/enforce/config/add/batch',
        data: this.formData,
        headers: {
          'Content-Type': 'application/json', //设置请求头请求格式为JSON
        },
      })
        .then((resp) => {
          //成功回调函数停止加载
          loading.close()
          console.log(resp, 'add result')
          if (resp.data.hasError && resp.data.msg) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: resp.data.msg,
              type: 'error',
            })
            //成功回调函数停止加载
            loading.close()
            return
          }
          if (!resp.data.hasError) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '创建成功',
              type: 'success',
            })
            let ts = this
            setTimeout(function () {
              //成功回调函数停止加载
              loading.close()
              ts.$router.push({
                name: 'finishProposal',
                query: { id: resp.data.result.configId },
              })
            }, 3000)
          }
        })
        .catch((resp) => {
          //成功回调函数停止加载
          loading.close()
          console.log('请求失败：' + resp.status + ',' + resp.statusText)
        })
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  top: 198px;
  padding: 0 24px !important;

  .searchInputWidth {
    .problemSelect {
      /deep/ .el-form-item__content {
        height: auto !important;
      }
    }
  }

  .title {
    position: relative;
    padding-left: 20px;
    padding-top: 14px;
    padding-bottom: 20px;
    font-size: 18px;

    &::before {
      position: absolute;
      content: '';
      width: 4px;
      height: 24px;
      left: 0;
      top: 14px;
      background: #265faa;
    }

    .subTitle {
      font-size: 14px;
    }
  }

  .submitBox {
    width: 100%;
    margin-top: 100px;
    text-align: center;
  }

  /*@media screen and (min-width: 1280px) and (max-width: 1366px){*/
  /*.searchInputWidth /deep/.el-form-item__label{*/
  /*width: 56px;*/
  /*}*/
  /*}*/

  .openBtn {
    padding: 0 8px 0 24px;
    color: #409eff;
    cursor: pointer;
    .down {
      -webkit-transform: rotate(180deg);
      transition: all 0.3s;
      vertical-align: 0;
    }

    .up {
      -webkit-transform: rotate(0deg);
      transition: all 0.3s;
      vertical-align: -1px;
    }
  }
}
</style>
